from PIL import Image
import os
import csv

def create_atlas_and_csv(image_folder, atlas_path, csv_path, tile_size):
    images = []
    coordinates = []

    # Load all images from the folder
    for filename in os.listdir(image_folder):
        if filename.endswith('.png'):
            img = Image.open(os.path.join(image_folder, filename))
            images.append((filename, img))

    # Determine the size of the atlas
    num_images = len(images)
    atlas_width = tile_size * (num_images // (tile_size) + 1)
    atlas_height = tile_size * (num_images // (tile_size) + 1)

    # Create a blank atlas
    atlas = Image.new('RGBA', (atlas_width, atlas_height))

    # Paste images into the atlas and record their coordinates
    x_offset, y_offset = 0, 0
    for filename, img in images:
        atlas.paste(img, (x_offset, y_offset))
        coordinates.append((filename, x_offset, y_offset))
        x_offset += tile_size
        if x_offset >= atlas_width:
            x_offset = 0
            y_offset += tile_size

    # Save the atlas
    atlas.save(atlas_path)

    # Write the coordinates to a CSV file
    with open(csv_path, 'w', newline='') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow(['filename', 'x', 'y'])
        for coord in coordinates:
            writer.writerow(coord)

# Example usage
create_atlas_and_csv(
        r'F:\gamedevelop\SoulslikeTRPGTemplate\Assets\Textures\Icons\IconsSeperate', 
        r'F:\gamedevelop\SoulslikeTRPGTemplate\Assets\Textures\Icons\Icons.png', 
        r'F:\gamedevelop\SoulslikeTRPGTemplate\Assets\Configs\CSV\Icons.csv', 16
    )
